package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    private String hostname;

    private String appBase;

    private Mapper mapper =new Mapper();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 加载解析相关的配置，web.xml
        initServer();
        loadServlet();


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap,mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    private void initServer() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element serverElement = (Element)rootElement.selectSingleNode("Service");
            initService(serverElement);

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private void initService(Element serverElement) {
        Element connectorElement = (Element) serverElement.selectSingleNode("Connector");
        String port = connectorElement.attributeValue("port");

        this.port = Integer.parseInt(port);

        Element engineElement = (Element) serverElement.selectSingleNode("Engine");


        List<HostMapper> hostsList = new ArrayList<>();

        //获取Host标签，每个Service下有多个Host
        List<Element> hosts = engineElement.elements("Host");
        for (int i = 0; i < hosts.size(); i++) {
            initHost(hosts.get(i),hostsList);
        }
        mapper.setPort(this.port);
        mapper.setHosts(hostsList);
    }

    private void initHost(Element hostElement, List<HostMapper> hostsList) {
        String name = hostElement.attributeValue("name");
        String appBase = hostElement.attributeValue("appBase");
        HostMapper hostMapper = new HostMapper();

        List<ContextMapper> contexts = new ArrayList<>();


        File baseFile = new File(appBase);
        if(!baseFile.exists() || baseFile.isFile()){
            return;
        }

        for (File file : baseFile.listFiles()){
            initContext(file, contexts);
        }
        hostMapper.setContexts(contexts);
        hostMapper.setAppBase(appBase);
        hostMapper.setName(name);
        hostsList.add(hostMapper);
    }

    private void initContext(File contextFile, List<ContextMapper> contexts) {
        if(!contextFile.exists() || contextFile.isFile()){
            return;
        }

        ContextMapper contextMapper = new ContextMapper();
        String name = contextFile.getName();
        contextMapper.setApplicationName(name);

        contextMapper.setApplicationName(name);

        List<WrapperMapper> wrapperMappers = new ArrayList<>();

        File wapperFile = new File(contextFile.getAbsolutePath());
        File[] files = contextFile.listFiles();
        for(File file : files){
            if("WEB-INF".equals(file.getName())){
                initWrapper(name, file, wrapperMappers);
            }
        }
        contextMapper.setWrappers(wrapperMappers);
        contextMapper.setApplicationPath(contextFile.getAbsolutePath());
        contexts.add(contextMapper);
    }

    private void initWrapper(String name, File webInfFile, List<WrapperMapper> wrapperMappers) {
        if(!webInfFile.exists() || webInfFile.isFile()){
            return;
        }
        File[] files = webInfFile.listFiles();
        FileInputStream fileInputStream = null;
        String webappClassPath = "";
        for(File file : files){
            if("web.xml".equals(file.getName())){
                try {
                    fileInputStream = new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            if("classes".equals(file.getName())){
                webappClassPath = file.getAbsolutePath();
            }
        }
        if(null == fileInputStream) {
            return;
        }
//        String absoluteApplicationPath = webInfFile.getParentFile().getAbsolutePath();

        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(fileInputStream);
            Element rootElement = document.getRootElement();

            List<Element> list = rootElement.selectNodes("//servlet");
            for (Element element : list) {

                // <servlet-name>lagou</servlet-name>
                Element servletName = (Element) element.selectSingleNode("servlet-name");
                String servletNameValue = servletName.getStringValue();
                //<servlet-class>server.LagouServlet</servlet-class>
                Element servletClass = (Element) element.selectSingleNode("servlet-class");
                String servletClassValue = servletClass.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletNameValue + "']");
                // /lagou
                String urlPattern = "/"+ name +servletMapping.selectSingleNode("url-pattern").getStringValue();

                //Users/webapps/demo1/server/LagouServlet.class
//                String classPath = absoluteApplicationPath+"/"+servletClassValue.replaceAll("\\.","/")+".classes";

                ClassLoader miniCatClassLoader = new WebAppClassLoader(name,Thread.currentThread().getContextClassLoader(), webappClassPath);
                HttpServlet value = (HttpServlet) Class.forName(servletClassValue,true,miniCatClassLoader).newInstance();
                WrapperMapper wrapper = new WrapperMapper(value, urlPattern);
                wrapperMappers.add(wrapper);
                servletMap.put(urlPattern, value);
            }

        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }



    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }



        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
